package tech.aistar.day12;

import java.io.*;
import java.util.List;

/**
 * 本类用来演示: 对象的序列化和反序列化
 *
 * @author: success
 * @date: 2022/8/3 10:42 上午
 */
public class ObjectDemo {
    public static final String PATH = "src/tech/aistar/day12/purcase.txt";
    public static void main(String[] args) {
        Purcase purcase = new Purcase("联合利华","def",78.8d);

        //save(PATH,purcase);

        Purcase p = read(PATH);
        System.out.println(p);
        //List<Purcase> list = readList(PATH);
        //for (Purcase p : list) {
        //    System.out.println(p);
        //}

    }

    //对象的序列化的过程
    //public static void save(String path,Purcase purcase){
    //    //追加写入
    //    //try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path))){
    //    try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path,true))){
    //
    //        out.writeObject(purcase);
    //        System.out.println("保存成功!");
    //    } catch (FileNotFoundException e) {
    //        e.printStackTrace();
    //    } catch (IOException e) {
    //        e.printStackTrace();
    //    }
    //}

    public static void save(String path,Purcase purcase){
        //追加写入
        try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path))){
        //try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path,true))){

            out.writeObject(purcase);
            System.out.println("保存成功!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //对象的反序列化
    public static Purcase read(String path){
        Purcase purcase = null;
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(path))){
            purcase = (Purcase) in.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return purcase;
    }

    public static List<Purcase> readList(String path){
        List<Purcase> purcaseList = null;
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(path))){
            purcaseList = (List<Purcase>) in.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return purcaseList;
    }
}
